package com.example.httpclient.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {
/*
    public static String capitalizeJsonKeys(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(String.class, new CapitalizeJsonKeysSerializer());
        objectMapper.registerModule(module);
        Object obj = objectMapper.readValue(json, Object.class);
        return objectMapper.writeValueAsString(obj);
    }

    private static class CapitalizeJsonKeysSerializer extends JsonSerializer<String> {
        @Override
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            String capitalizedValue = value.substring(0, 1).toUpperCase() + value.substring(1);
            gen.writeFieldName(capitalizedValue);
        }
    }
 */
    public static String capitalizeJsonKeys(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        Object obj = objectMapper.readValue(json, Object.class);
        capitalizeJsonKeys(obj);
        return objectMapper.writeValueAsString(obj);
    }

    private static void capitalizeJsonKeys(Object obj) {
        if (obj instanceof Map) {
            Map map = (Map) obj;
            Map<String, Object> newMap = new HashMap<>();
            for (Object key : map.keySet()) {
                String newKey = capitalizeFirstLetter((String) key);
                Object value = map.get(key);
                newMap.put(newKey, value);
                capitalizeJsonKeys(value);
            }
            map.clear();
            map.putAll(newMap);
        } else if (obj instanceof List) {
            List list = (List) obj;
            for (int i = 0; i < list.size(); i++) {
                Object value = list.get(i);
                capitalizeJsonKeys(value);
            }
        } else if (obj instanceof String) {
            String str = (String) obj;
            capitalizeFirstLetter(str);
        }
    }

    private static String capitalizeFirstLetter(String str) {
        if (str != null && str.length() > 0) {
            return str.substring(0, 1).toUpperCase() + str.substring(1);
        }
        return str;
    }
}
